package jhta;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.UIManager;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;


public class BookInput extends JInternalFrame {
	Main main;
	JavaDBConnection jdbc;
	Connection conn;
	
	BookVo bv;
	
	int codeNo;
	int memberNo;
	
	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
	DecimalFormat df = new DecimalFormat("####-##-##");
	
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_1;
	private JComboBox comboBox_1;
	private JLabel lblNewLabel_3;
	private JLabel lblNewLabel_4;
	private JLabel lblNewLabel_5;
	private JLabel lblNewLabel_6;
	private JLabel lblNewLabel_7;
	private JTextField txtNo;
	private JTextField txtName;
	private JTextField txtAuthor;
	private JTextField txtPublisher;
	private JLayeredPane layeredPane;
	private JLabel lblNewLabel_8;
	private JLayeredPane layeredPane_1;
	private JLayeredPane layeredPane_2;
	private JLabel lblNewLabel_10;
	private JComboBox comboBox_2;
	private JButton btnSave;
	private JButton btnReset;
	private JButton btnCancel;
	private JTextField txtBig;
	private JLabel label;
	private JLabel label_1;
	private JSpinner spinner;
	private JTextField txtRdate;
	private JDatePickerImpl datePicker;
	private JDatePickerImpl datePicker1;
	private JTextField txtPdate;

	public BookInput(Main main) {
		super("도서 정보 입력", false, true, false, true);
		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentHidden(ComponentEvent e) {
				clear();
			}
		});
		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameActivated(InternalFrameEvent arg0) {
				comboBoxAdminSetting();
				comboBoxSmallCodeSetting();
			}
		});
		setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 430, 450);
		getContentPane().setLayout(null);
		getContentPane().add(getLayeredPane_1());
		getContentPane().add(getLayeredPane_1_1());
		getContentPane().add(getLayeredPane_2());
		getContentPane().add(getLblNewLabel_8());
		getContentPane().add(getBtnSave());
		getContentPane().add(getBtnReset());
		getContentPane().add(getBtnCancel());
		
		this.main = main;
		
		jdbc = new JavaDBConnection();
		conn = jdbc.getConn();
		
		txtBig.setText("도서");
		comboBoxSmallCodeSetting();
		comboBoxAdminSetting();
		bookNoSetting();
		
		clear();

	}
	
	// DB에서 소분류 검색하고 콤보박스에 채워줌
	public void comboBoxSmallCodeSetting(){
		comboBox_1.removeAllItems();
		String sql = "select distinct code_name from code "
				   + "where code_big = 'A1' and code_small is not null";
		
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			if(pstmt.executeUpdate() > 0){
				ResultSet rs = pstmt.executeQuery();
				
				while(rs.next()) comboBox_1.addItem(rs.getString("code_name"));

				rs.close();
			}else{
				JOptionPane.showMessageDialog(null, "소분류 항목을 불러올 수 없습니다");
			}
			
			pstmt.close();
		}catch(Exception ex){ex.getStackTrace();}
	}
	
	// DB에서 관리자 목록을 검색하고 콤보박스에 뿌려줌
	public void comboBoxAdminSetting(){
		comboBox_2.removeAllItems();
		String sql = "select b.name from bookmember b inner join code c "
				   + "on b.code_no = c.code_no "
				   + "where c.code_big = ?";
		
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "A2");

			if(pstmt.executeUpdate() > 0){
				ResultSet rs = pstmt.executeQuery();
				
				comboBox_2.addItem(Main.USER_NAME);
				while(rs.next()) comboBox_2.addItem(rs.getString(1));

				rs.close();
			}else{
				JOptionPane.showMessageDialog(null, "관리자 항목을 불러올 수 없습니다.");
			}
			pstmt.close();
		}catch(Exception ex){ex.getStackTrace();}
	}
	
	// 책번호를 시퀀스에서 한번 불러와서 저장해 놓음
	// 취소나 다시입력 버튼을 눌렀을 경우에 책 번호가 증가하지 않도록
	public void bookNoSetting(){
		String sql = "select seq_book_no.nextval from dual";
		
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
				
			if(rs.next()) txtNo.setText(rs.getInt(1) + "");
			else JOptionPane.showMessageDialog(null, "(seq_book_no.nextval) 시퀀스를 불러올 수 없습니다.");
			
			rs.close();
			pstmt.close();
		}catch(Exception ex){ex.getStackTrace();}
	}
	
	// 소분류를 선택했을 때 코드번호(code_no)를 검색해서 codeNo 변수에 저장
	public int getCodeNo(){
		String sql = "select code_no from code where code_big = ? and code_name = ?";
		
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "A1");
			pstmt.setString(2, comboBox_1.getSelectedItem().toString());
			
			if(pstmt.executeUpdate() > 0){
				ResultSet rs = pstmt.executeQuery();
				if(rs.next()) codeNo = rs.getInt(1);
				rs.close();
			}else{
				JOptionPane.showMessageDialog(null, "(code_no)를 불러올 수 없습니다.");
			}
			pstmt.close();
		}catch(Exception ex){ex.getStackTrace();}
		
		return codeNo;
	}
	
	// 관리자를 선택했을 때 회원번호(member_no)를 검색해서 저장 memberNo 변수에 저장
	public int getMemberNo(){
		String sql = "select no from bookmember where name = ?";
		
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, comboBox_2.getSelectedItem().toString());
			
			if(pstmt.executeUpdate() > 0){
				ResultSet rs = pstmt.executeQuery();
				if(rs.next()) memberNo = rs.getInt(1);
				rs.close();
			}else{
				JOptionPane.showMessageDialog(null, "(member_no)를 불러올 수 없습니다.");
			}
			pstmt.close();
		}catch(Exception ex){ex.getStackTrace();}
		
		return memberNo;
	}
	
	// 데이터베이스에 저장
	public void insertDB(){
		String sql = "insert into book values (?, ?, ?, ?, to_date(?, 'yyyy-mm-dd'), to_date(?, 'yyyy-mm-dd'),? ,? ,? ,?)";
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			pstmt.setInt(1, Integer.parseInt(txtNo.getText()));
			pstmt.setString(2, txtName.getText());
			pstmt.setString(3, txtAuthor.getText());
			pstmt.setString(4, txtPublisher.getText());
			pstmt.setString(5, txtPdate.getText());
			pstmt.setString(6, txtRdate.getText());
			pstmt.setInt(7, Integer.parseInt(spinner.getValue().toString()));
			pstmt.setInt(8, Integer.parseInt(spinner.getValue().toString()));
			pstmt.setInt(9, getMemberNo());
			pstmt.setInt(10, getCodeNo());
			
			if(pstmt.executeUpdate() > 0) {
				JOptionPane.showMessageDialog(null, "잘 저장되었습니다");
				clear();
				bookNoSetting();
			}else{
				JOptionPane.showMessageDialog(null, "저장 실패!!");
			}
			
			pstmt.close();
		}catch(Exception ex){ex.getStackTrace();
			System.out.println("insert 에러");
		}
	}
	
	// 책 이름 중복 검사
	public boolean overlapName(){
		String sql = "select name from book where name like ?";
		String find = txtName.getText();
		try{
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "%" + find + "%");
			if(pstmt.executeUpdate() > 0){
				return true;
			}
			pstmt.close();
			
		}catch(Exception ex){ex.getStackTrace();
			System.out.println("overlap 에러");
		}
		return false;
	}
	
	// 모든 항목들 초기화
	public void clear(){
		txtName.setText("");
		txtAuthor.setText("");
		txtPublisher.setText("");
		txtPdate.setText("");
		txtRdate.setText(sd.format(new Date()));
		comboBox_1.setSelectedIndex(0);
		comboBox_2.setSelectedIndex(0);
		spinner.setValue(1);
		txtRdate.setText(sd.format(new Date()));
		txtPdate.setText(sd.format(new Date()));
	}
	
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("대  분  류 :");
			lblNewLabel.setForeground(Color.BLACK);
			lblNewLabel.setBounds(-4, 22, 67, 15);
			lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return lblNewLabel;
	}
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("소  분  류* :");
			lblNewLabel_1.setBounds(-4, 52, 67, 15);
			lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return lblNewLabel_1;
	}
	private JLabel getLblNewLabel_3() {
		if (lblNewLabel_3 == null) {
			lblNewLabel_3 = new JLabel("도서번호* :");
			lblNewLabel_3.setForeground(Color.BLACK);
			lblNewLabel_3.setBounds(-4, 22, 69, 15);
			lblNewLabel_3.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return lblNewLabel_3;
	}
	private JLabel getLblNewLabel_4() {
		if (lblNewLabel_4 == null) {
			lblNewLabel_4 = new JLabel("도  서  명* :");
			lblNewLabel_4.setBounds(-4, 52, 69, 15);
			lblNewLabel_4.setForeground(Color.BLACK);
			lblNewLabel_4.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return lblNewLabel_4;
	}
	private JLabel getLblNewLabel_5() {
		if (lblNewLabel_5 == null) {
			lblNewLabel_5 = new JLabel("저        자 :");
			lblNewLabel_5.setBounds(-4, 82, 69, 15);
			lblNewLabel_5.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return lblNewLabel_5;
	}
	private JLabel getLblNewLabel_6() {
		if (lblNewLabel_6 == null) {
			lblNewLabel_6 = new JLabel("출  판  사 :");
			lblNewLabel_6.setBounds(-4, 112, 69, 15);
			lblNewLabel_6.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return lblNewLabel_6;
	}
	private JLabel getLblNewLabel_7() {
		if (lblNewLabel_7 == null) {
			lblNewLabel_7 = new JLabel("출  판  일 :");
			lblNewLabel_7.setBounds(-4, 142, 69, 15);
			lblNewLabel_7.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return lblNewLabel_7;
	}
	private JTextField getTxtNo() {
		if (txtNo == null) {
			txtNo = new JTextField();
			txtNo.setBounds(75, 17, 187, 25);
			txtNo.setEnabled(false);
			txtNo.setColumns(10);
		}
		return txtNo;
	}
	private JTextField getTxtName() {
		if (txtName == null) {
			txtName = new JTextField();
			txtName.setBounds(75, 47, 187, 25);
			txtName.setColumns(10);
		}
		return txtName;
	}
	private JTextField getTxtAuthor() {
		if (txtAuthor == null) {
			txtAuthor = new JTextField();
			txtAuthor.setBounds(75, 77, 187, 25);
			txtAuthor.setColumns(10);
		}
		return txtAuthor;
	}
	private JTextField getTxtPublisher() {
		if (txtPublisher == null) {
			txtPublisher = new JTextField();
			txtPublisher.setBounds(75, 107, 187, 25);
			txtPublisher.setColumns(10);
		}
		return txtPublisher;
	}
	private JLayeredPane getLayeredPane_1() {
		if (layeredPane == null) {
			layeredPane = new JLayeredPane();
			layeredPane.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null), "\uBD84\uB958", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
			layeredPane.setBounds(16, 16, 274, 85);
			layeredPane.setLayout(null);
			layeredPane.add(getLblNewLabel());
			layeredPane.add(getLblNewLabel_1());
			layeredPane.add(getComboBox_1());
			layeredPane.add(getTxtBig());
		}
		return layeredPane;
	}
	private JLabel getLblNewLabel_8() {
		if (lblNewLabel_8 == null) {
			lblNewLabel_8 = new JLabel("<html><center>이미지를<br>추가하려면<br>클릭하세요</center></html>", SwingConstants.CENTER);
			lblNewLabel_8.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
			lblNewLabel_8.setBounds(302, 21, 100, 100);
		}
		return lblNewLabel_8;
	}
	private JLayeredPane getLayeredPane_1_1() {
		if (layeredPane_1 == null) {
			layeredPane_1 = new JLayeredPane();
			layeredPane_1.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null), "\uB3C4\uC11C\uC815\uBCF4", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
			layeredPane_1.setBounds(16, 111, 274, 203);
			layeredPane_1.setLayout(null);
			layeredPane_1.add(getLblNewLabel_3());
			layeredPane_1.add(getLblNewLabel_4());
			layeredPane_1.add(getLblNewLabel_5());
			layeredPane_1.add(getLblNewLabel_6());
			layeredPane_1.add(getLblNewLabel_7());
			layeredPane_1.add(getTxtNo());
			layeredPane_1.add(getTxtName());
			layeredPane_1.add(getTxtAuthor());
			layeredPane_1.add(getTxtPublisher());
			layeredPane_1.add(getLabel_1());
			layeredPane_1.add(getSpinner());
			layeredPane_1.add(getDatePicker());
			layeredPane_1.add(getTxtPdate());
		}
		return layeredPane_1;
	}
	private JLayeredPane getLayeredPane_2() {
		if (layeredPane_2 == null) {
			layeredPane_2 = new JLayeredPane();
			layeredPane_2.setBounds(16, 324, 274, 85);
			layeredPane_2.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null), "\uC791\uC131\uC790", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
			layeredPane_2.add(getLblNewLabel_10());
			layeredPane_2.add(getComboBox_2());
			layeredPane_2.add(getLabel());
			layeredPane_2.add(getTxtRdate());
			layeredPane_2.add(getDatePicker_1());
		}
		return layeredPane_2;
	}
	private JLabel getLblNewLabel_10() {
		if (lblNewLabel_10 == null) {
			lblNewLabel_10 = new JLabel("관  리  자 :");
			lblNewLabel_10.setHorizontalAlignment(SwingConstants.RIGHT);
			lblNewLabel_10.setBounds(-4, 22, 67, 15);
		}
		return lblNewLabel_10;
	}
	private JComboBox getComboBox_1() {
		if (comboBox_1 == null) {
			comboBox_1 = new JComboBox();
			comboBox_1.setBounds(75, 47, 187, 25);
		}
		return comboBox_1;
	}
	private JComboBox getComboBox_2() {
		if (comboBox_2 == null) {
			comboBox_2 = new JComboBox();
			comboBox_2.setBounds(75, 17, 187, 25);
		}
		return comboBox_2;
	}
	private JButton getBtnSave() {
		if (btnSave == null) {		
			btnSave = new JButton("저장");
			btnSave.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(txtName.getText().trim().equals("")){
						JOptionPane.showMessageDialog(null, "(도서명) 항목은 필수사항입니다. 입력해주세요.");
						
					}else if(overlapName()){
						int yn = 0;
						yn = JOptionPane.showConfirmDialog(null, "유사한 혹은 중복된 책이 있습니다. 계속 진행하시겠습니까?");
						if(yn == JOptionPane.OK_OPTION){
							insertDB();
						}else if(yn == JOptionPane.NO_OPTION){
							yn = JOptionPane.showConfirmDialog(null, "책 리스트를 확인 하시겠습니까?");
							if(yn == JOptionPane.OK_OPTION){
								main.openBookUpdate();
								main.bUpdate.getTxtInput().setText(txtName.getText());
								main.bUpdate.searchDB();
							}
						}
					}else{
						insertDB();
					}
				}
			});
			btnSave.setBounds(302, 209, 100, 100);
		}
		return btnSave;
	}
	private JButton getBtnReset() {
		if (btnReset == null) {
			btnReset = new JButton("다시입력");
			btnReset.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					clear();
				}
			});
			btnReset.setBounds(302, 319, 100, 40);
		}
		return btnReset;
	}
	private JButton getBtnCancel() {
		if (btnCancel == null) {
			btnCancel = new JButton("취소");
			btnCancel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					clear();
				}
			});
			btnCancel.setBounds(302, 369, 100, 40);
		}
		return btnCancel;
	}
	private JTextField getTxtBig() {
		if (txtBig == null) {
			txtBig = new JTextField();
			txtBig.setEnabled(false);
			txtBig.setBounds(75, 17, 187, 25);
			txtBig.setColumns(10);
		}
		return txtBig;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("작  성  일 :");
			label.setHorizontalAlignment(SwingConstants.RIGHT);
			label.setBounds(-4, 52, 67, 15);
		}
		return label;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("권        수 :");
			label_1.setHorizontalAlignment(SwingConstants.RIGHT);
			label_1.setBounds(-4, 172, 69, 15);
		}
		return label_1;
	}
	private JSpinner getSpinner() {
		if (spinner == null) {
			spinner = new JSpinner();
			spinner.setModel(new SpinnerNumberModel(new Integer(1), new Integer(1), null, new Integer(1)));
			spinner.setBounds(75, 167, 187, 25);
		}
		return spinner;
	}
	private JTextField getTxtRdate() {
		if (txtRdate == null) {
			txtRdate = new JTextField();
			txtRdate.setBounds(75, 47, 142, 25);
			txtRdate.setColumns(10);
		}
		return txtRdate;
	}
	private JDatePickerImpl getDatePicker(){
		if (datePicker == null) {
			UtilDateModel uModel = new UtilDateModel();
			JDatePanelImpl datePanel = new JDatePanelImpl(uModel);
			datePicker = new JDatePickerImpl(datePanel);
			datePicker.setBorder(null);			
			datePicker.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					txtPdate.setText(sd.format((Date)datePicker.getModel().getValue()));
				}
			});
			datePicker.getJFormattedTextField().setVisible(false);
			datePicker.setSize(45, 27);
			datePicker.setLocation(217, 135);
			
		}
		return datePicker;
	}
	private JTextField getTxtPdate() {
		if (txtPdate == null) {
			txtPdate = new JTextField();
			txtPdate.setBounds(75, 137, 142, 25);
			txtPdate.setColumns(10);
		}
		return txtPdate;
	}
	private JDatePickerImpl getDatePicker_1(){
		if (datePicker1 == null) {
			UtilDateModel uModel = new UtilDateModel();
			JDatePanelImpl datePanel = new JDatePanelImpl(uModel);
			datePicker1 = new JDatePickerImpl(datePanel);
			datePicker1.setBorder(null);
			datePicker1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					txtRdate.setText(sd.format((Date)datePicker1.getModel().getValue()));
				}
			});
			datePicker1.getJFormattedTextField().setVisible(false);
			datePicker1.setSize(45, 27);
			datePicker1.setLocation(217, 45);
			
		}
		return datePicker1;
	}
}